/*
 * 工具类
 * @Author: Ray
 * @Date:   2018-01-31
 */
;
(function(window) {
    'use strict';
    var hooks = {};

    hooks.isDebug = true;

    hooks.isJson = function(obj) {
        var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        return isjson;
    };

    hooks.isString = function(obj) {
        return this.isTargetType(obj, "string") && obj != null && obj != undefined;
    };

    hooks.isTargetType = function(obj, typeString) {
        return typeof obj === typeString;
    };

    hooks.isFunction = function(value) {
        return typeof value === 'function';
    };

    hooks.isArray = function(value) {
        return Object.prototype.toString.call(value) === '[object Array]';
    };

    hooks.isObject = function(value) {
        // Avoid a V8 JIT bug in Chrome 19-20.
        // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
        var type = typeof value;
        return !!value && type == 'object';
    };

    /**
     * 补零
     * @param {Number} num 数字
     * @param {Number} totalLen 总长度
     */
    hooks.fillZero = function(num, totalLen, direction) {
        // return (Array(totalLen).join(0) + num).slice(-totalLen);
        num = num + '';
        direction = direction || 'left';
        var zeroLen = totalLen - num.length + 1,
            zeroArr = Array(zeroLen).join(0);

        if (direction == 'left') {
            return zeroArr + num;
        }
        return num + zeroArr;
    };

    /**
     * 二进制转Base64
     * @param {ArrayBuffer} buffer 二进制数据
     */
    hooks.arrayBufferToBase64 = function(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    };

    /**
     * Base64转二进制
     * @param {String} base64 base64串
     */
    hooks.base64ToArrayBuffer = function(base64) {
        var binary_string = window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    };

    /**
     * utf16转utf8
     * @param {String} utf16Str utf16字符串
     */
    hooks.utf16ToUtf8 = function(utf16Str) {
        var utf8Arr = [];
        var byteSize = 0;
        for (var i = 0; i < utf16Str.length; i++) {
            //获取字符Unicode码值
            var code = utf16Str.charCodeAt(i);

            //如果码值是1个字节的范围，则直接写入
            if (code >= 0x00 && code <= 0x7f) {
                byteSize += 1;
                utf8Arr.push(code);

                //如果码值是2个字节以上的范围，则按规则进行填充补码转换
            } else if (code >= 0x80 && code <= 0x7ff) {
                byteSize += 2;
                utf8Arr.push((192 | (31 & (code >> 6))));
                utf8Arr.push((128 | (63 & code)))
            } else if ((code >= 0x800 && code <= 0xd7ff) ||
                (code >= 0xe000 && code <= 0xffff)) {
                byteSize += 3;
                utf8Arr.push((224 | (15 & (code >> 12))));
                utf8Arr.push((128 | (63 & (code >> 6))));
                utf8Arr.push((128 | (63 & code)))
            } else if (code >= 0x10000 && code <= 0x10ffff) {
                byteSize += 4;
                utf8Arr.push((240 | (7 & (code >> 18))));
                utf8Arr.push((128 | (63 & (code >> 12))));
                utf8Arr.push((128 | (63 & (code >> 6))));
                utf8Arr.push((128 | (63 & code)))
            }
        }

        return utf8Arr
    };

    /**
     * utf8转utf16
     * @param {Array} utf8Arr utf8数组
     */
    hooks.utf8ToUtf16 = function(utf8Arr) {
        var utf16Str = '';

        for (var i = 0; i < utf8Arr.length; i++) {
            //每个字节都转换为2进制字符串进行判断
            var one = utf8Arr[i].toString(2);

            //正则表达式判断该字节是否符合>=2个1和1个0的情况
            var v = one.match(/^1+?(?=0)/);

            //多个字节编码
            if (v && one.length == 8) {
                //获取该编码是多少个字节长度
                var bytesLength = v[0].length;

                //首个字节中的数据,因为首字节有效数据长度为8位减去1个0位，再减去bytesLength位的剩余位数
                var store = utf8Arr[i].toString(2).slice(7 - bytesLength);
                for (var st = 1; st < bytesLength; st++) {
                    //后面剩余字节中的数据，因为后面字节都是10xxxxxxx，所以slice中的2指的是去除10
                    store += utf8Arr[st + i].toString(2).slice(2)
                }

                //转换为Unicode码值
                utf16Str += String.fromCharCode(parseInt(store, 2));

                //调整剩余字节数
                i += bytesLength - 1
            } else {
                //单个字节编码，和Unicode码值一致，直接将该字节转换为UTF-16
                utf16Str += String.fromCharCode(utf8Arr[i])
            }
        }

        return utf16Str
    };

    //打印日志
    hooks.baseLog = function(type, args) {
        var self = this;
        if (!self.isDebug) {
            return;
        }
        if (window.VConsole && !window.$logInfo) {
            var disableLogFiles = ['main_win.html','install_detail_win.html']; // 禁用vConsole的文件
            var filename = location.href;
            filename = filename.substr(filename.lastIndexOf('/') + 1);
            if (disableLogFiles.indexOf(filename) === -1) {
                window.$VConsole = new VConsole();
            };
        }
        window.$logInfo = console.info;
        window.$logInfo.apply(null,args);

        var filename = location.href;
        filename = filename.substr(filename.lastIndexOf('/') + 1);

        var d = new Date(),
            dStr = '['
            // + d.getFullYear() + '-' 
            +
            self.fillZero(d.getMonth() + 1, 2) + '-' +
            self.fillZero(d.getDate(), 2) + ' ' +
            self.fillZero(d.getHours(), 2) + ':' +
            self.fillZero(d.getMinutes(), 2) + ':' +
            self.fillZero(d.getSeconds(), 2) + '.' +
            self.fillZero(d.getMilliseconds(), 2) + ']',
            logs = [],
            item;

        for (var i = 0, len = args.length; i < len; i++) {
            item = args[i];
            if (self.isFunction(item)) {
                logs.push('function');
            } else if (self.isObject(item) || self.isArray(item)) {
                logs.push(JSON.stringify(item));
            } else if (item === null) {
                logs.push('null');
            } else if (item === undefined) {
                logs.push('undefined');
            } else if (item === NaN) {
                logs.push('NaN');
            } else {
                logs.push(item);
            }
        }

        switch (type) {
            case 'warn':
                console.warn(dStr + filename + ' ' + logs.join(' '));
            break;
            case 'error':
                console.error(dStr + filename + ' ' + logs.join(' '));
            break;
            default:
                console.log(dStr + filename + ' ' + logs.join(' '));
            break;
        }
    };

    //打印日志
    hooks.log = function() {
        hooks.baseLog('log', arguments);
    }

    //打印日志
    hooks.logWarn = function() {
        hooks.baseLog('warn', arguments);
    }

    //打印日志
    hooks.logError = function() {
        hooks.baseLog('error', arguments);
    }

    /**
     * 检查门锁类型是否正确
     * @param {String} model 类型
     */
    hooks.checkLockModel = function(model) {
        if (model && $api.trimAll(model) == '未知') {
            return false;
        }
        return true;
    };

    /**
     * 格式化电量
     * @param {Number} power 电量
     */
    hooks.getPower = function(power) {
        if (!power) {
            return 0;
        }

        power = Number(power);
        if (power < 0) {
            power = 0;
        }
        if (power > 100) {
            power = 100;
        }
        return power;
    };

    hooks.sort = function(arr) {
        var s;
        for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr.length; j++) {
                if (arr[j] > arr[j + 1]) {
                    s = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = s;
                }
            }
        }
        return arr
    };

    //复制工单信息
    hooks.copyTicketInfo = function(text) {
        text = text.replace(/\s+/g, "").replace(/<\/div>/gim, "\n")
            .replace(/<\/?[^>]*>/gim, "").replace(/&nbsp;/gim, " ")

        var clipBoard = api.require('clipBoard');
        clipBoard.set({
            value: text
        }, function(ret, err) {});
    };

    /**
     * 比较版本号
     * @param {String} v1 版本1
     * @param {String} v2 版本2
     * 0:无变化，-1:v1大于v2，1:v1小于v2 
     */
    hooks.compareVersion = function(v1, v2) {
        if (v1 == v2) {
            return 0;
        }

        var v1Arr = v1.split('.'),
            v2Arr = v2.split('.'),
            v1Len = v1Arr.length,
            v2Len = v2Arr.length;

        if (v1Len != v2Len) {
            return 1;
        }

        for (var i = 0; i < v1Len; i++) {
            if (parseInt(v1Arr[i]) < parseInt(v2Arr[i])) {
                return 1;
            }
        }

        return -1;
    };

    window.$util = hooks;

})(window);